<?php
function _A($s = true, $m = 'OK', $d = array()) {
	exit(my_json_encode(array('s' => $s, 'm' => $m, 'd' => $d)));
}

function my_json_encode($arr) {
	$parts = array();
	$is_list = false;
	//Find out if the given array is a numerical array
	$keys = array_keys($arr);
	$max_length = count($arr) - 1;
	if (($keys[0] === 0) && ($keys[$max_length] === $max_length)) {//See if the first key is 0 and last key is length - 1
		$is_list = true;
		for ($i = 0; $i < count($keys); $i++) {//See if each key correspondes to its position
			if ($i != $keys[$i]) {//A key fails at position check.
				$is_list = false;
				//It is an associative array.
				break;
			}
		}
	}
	foreach ($arr as $key => $value) {
		if (is_array($value)) {//Custom handling for arrays
			if ($is_list)
				$parts[] = my_json_encode($value);
			/* :RECURSION: */
			else
				$parts[] = '"' . $key . '":' . my_json_encode($value);
			/* :RECURSION: */
		} else {
			$str = '';
			if (!$is_list)
				$str = '"' . $key . '":';
			//Custom handling for multiple data types
			if (!is_string($value) && is_numeric($value) && $value < 2000000000)
				$str .= $value;
			//Numbers
			elseif ($value === false)
				$str .= 'false';
			//The booleans
			elseif ($value === true)
				$str .= 'true';
			else
				$str .= '"' . addslashes($value) . '"';
			//All other things
			// :TODO: Is there any more datatype we should be in the lookout for? (Object?)
			$parts[] = $str;
		}
	}
	$json = implode(',', $parts);
	if ($is_list)
		return '[' . $json . ']';
	//Return numerical JSON
	return '{' . $json . '}';
	//Return associative JSON
}

if(!function_exists('curl_get')){
    function curl_get($url){
        //初始化
        $ch = curl_init();
        // 执行并获取HTML文档内容
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }
}


if(!function_exists('get_jc_cz')){
    function get_jc_cz(){
        $arr = [
            '1' => [
                'title'      => '12个月',
                'price'      => yzl_config('jc.jc_member_price'),
                'type'       => '普通会员',
                'order_type' => 'member',
            ],
            '2' => [
                'title'      => '12个月',
                'price'      => yzl_config('jc.jc_vip_price'),
                'type'       => 'VIP会员',
                'order_type' => 'vip_member',
            ],
        ];
        return $arr;
    }
}


if(!function_exists('jc_category_to_slider_type')){
    function jc_category_to_slider_type($category_id){
        $arr = [];
        return isset($arr[$category_id]) ? $arr[$category_id] : null;
    }
}


function jc_cart_list($user_id, $ids = []){
    $map = [
        'user_id'   => $user_id
    ];
    if($ids){
        $map['id'] = ['in', $ids];
    }
    $cart_list = M('JcCart')->where($map)->field('id,goods_id,attr_id,goods_num')->order('id desc')->select();
    $total_money = 0;
    $total_num = 0;
    if($cart_list){
        if($goods_ids = array_column($cart_list, 'goods_id')) {
            $goods_list = M('JcGoods')->where(['id'=>['in', $goods_ids]])->getField('id,goods_name,img,price,stock_num,status');
        }else{
            $goods_list = [];
        }
        if($attr_ids = array_column($cart_list, 'attr_id')) {
            $attr_list = M('JcGoodsAttr')->where(['id'=>['in', $attr_ids]])->getField('id,goods_id,name,dif,num');
        }else{
            $attr_list = [];
        }
        foreach ($cart_list as $key => &$row) {
            if(isset($goods_list[$row['goods_id']])){
                $goods = $goods_list[$row['goods_id']];
                $goods['attr_name'] = '';
                if(isset($attr_list[$row['attr_id']])){
                    $attr = $attr_list[$row['attr_id']];
                    if($attr['goods_id'] == $goods['id']){
                        $goods['price'] += $attr['dif'];
                        $goods['stock_num'] = $attr['num'];
                        $goods['attr_name'] = $attr['name'];
                    }
                }
                $total_money += $goods['price']*$row['goods_num'];
                $total_num += $row['goods_num'];
                $row = array_merge($goods, $row);
            }
        }
    }
    return ['cart_list'=>$cart_list, 'total_money'=>$total_money, 'total_num'=>$total_num];
}

if(!function_exists('update_member_time')){
    function update_member_time($user_id, $member_type){
        $shop_model = M('nearby_shop');
        $shop = $shop_model->where(['uid' => $user_id])->find();
        $now_time = time();
        if ($shop) {
            $shop_up = [];
            switch ($member_type) {
                case 'member':
                    // 开通普通会员订单
                    if ($shop['member_grade'] == 0) {
                        $shop_up['member_grade'] = 1;
                        $shop_up['member_expire'] = strtotime('+1 year');
                    } else if ($shop['member_grade'] == 1) {
                        if ($shop['member_expire'] > $now_time) {
                            $shop_up['member_expire'] = strtotime('+1 year', $shop['member_expire']);
                        } else {
                            $shop_up['member_expire'] = strtotime('+1 year');
                        }
                    }
                    break;
                case 'vip_member':
                    // 开通vip会员订单
                    if ($shop['member_grade'] == 0) {
                        $shop_up['member_grade'] = 2;
                        $shop_up['member_expire'] = strtotime('+1 year');
                    } else if ($shop['member_grade'] == 2) {
                        if ($shop['member_expire'] > $now_time) {
                            $shop_up['member_expire'] = strtotime('+1 year', $shop['member_expire']);
                        } else {
                            $shop_up['member_expire'] = strtotime('+1 year');
                        }
                    }
                    break;
                default:

                    break;
            }
            if (!empty($shop_up)) {
                $shop_model->where(['id' => $shop['id']])->save($shop_up);
                return ['status'=>true];
            }else{
                return ['status' => false, 'msg' => "类型不匹配"];
            }
        }
        return ['status' => false, 'msg' => "店铺不存在"];
    }
}
if(!function_exists('jc_goods_pay_complete')){
    /**
     * 集采商品订单支付完成
     * @param [type] $order_id
     * @return void
     */
    function jc_goods_pay_complete($order_id){
        $order_goods = M('JcOrderGoods')->where(['order_id'=>$order_id])->select();
        $goodsModel = M('JcGoods');
        if($order_goods){
            // 销量
            foreach ($order_goods as $key => $goods) {
                $goodsModel->where(['id'=>$goods['goods_id']])->setInc('sales_num', $goods['buy_num']);
            }
        }
    }
}

if(!function_exists('jc_order_btn')){
    function jc_order_bnt($order){
        $btn = [];
        if($order['order_status'] == 1 && $order['shipping_status'] == 1){
            // $btn[] = 'confirm_receipt';
        }
        return $btn;
    }
}

if(!function_exists('jc_order_status_msg')){
    function jc_order_status_msg($order){
        $status_msg = '';
        // if($order['order_status'] == -1){
        //     $status_msg  = '交易已关闭'; 
        // }

        // if($order['order_status'] == 0){
        //     $status_msg  = '交易已取消'; 
        // }

        // if($order['order_status'] == 1){
        //     if($order['pay_status'] == 0){
        //         $status_msg  = '待付款';
        //     }
            
        //     if($order['pay_status'] == 1){
        //         if($order['shipping_status'] == 0){
        //             $status_msg  = '待发货';    
        //         }
        //         if($order['shipping_status'] == 1){
        //             $status_msg  = '待收货'; 
        //         }
        //     }
        // }
        // if($order['order_status'] == 2){
        //     $status_msg  = '已完成'; 
        // }
        // if(isset($order['del_status']) && $order['del_status'] == 1){
        //     $status_msg  = '已删除'; 
        // }
        // 新版
        switch ($order['order_status']) {
            case '1':// 创建状态
                $status_msg = '待确定';
                break;
            case '2':
                $status_msg = '已确认';
                break;
            default:
                break;
        }
        return $status_msg;
    }
}

/**
 * 两个时间相差的月份
 * @param unknown $date1 为结束日期  例 2018-12
 * @param unknown $date2 为开始日期  例 2017-11
 * @param string $tags   日期间隔符号
 * @return   相差的月份数量
 */
function getMonthNum( $date1, $date2, $tags='-' ){
    $date1 = explode($tags, $date1);
    $date2 = explode($tags, $date2);
    return abs($date1[0] - $date2[0]) * 12 - $date2[1] + abs($date1[1]);
}

/**
 * 返回今日开始和结束的时间戳
 * @return array
 */
function today(){
    return [
        mktime(0, 0, 0, date('m'), date('d'), date('Y')),
        mktime(23, 59, 59, date('m'), date('d'), date('Y'))
    ];
}

if(!function_exists('member_no_like')){
    /**
     * 会员号点赞接口
     * @author 张亚伟<1743325520@qq.com>
     * @DateTime 2018-11-28
     * @param    string  $member_no    会员号
     * @param    int     $source       来源类型
     * @param    int     $source_id    来源id
     * @param    int     $like_num     数量
     * @return   array
     */
    function member_no_like($member_no, $source, $source_id, $like_num = 1)
    {
        if(empty($member_no)){
            return ['status'=>0, 'msg'=>'会员号不存在'];
        }
        $member_no_info = M('member_no')->where(['member_no'=>$member_no])->find();
        if(empty($member_no_info)){
            return ['status'=>0, 'msg'=>'会员号不存在'];
        }
        if(!$member_no_info['is_buy']){
            return ['status'=>0, 'msg'=>'未购买过茶叶，无法参加'];
        }
        $member_no_id = $member_no_info['id'];
        $model = M('member_no_like');
        switch ($source) {
            case '1':
                // 点赞
                $today = today();
                $has = $model->where(['member_no_id'=>$member_no_id, 'source'=>$source, 'source_id'=>$source_id])->order('id desc')->find();
                if($has && date('Y-m-d', $has['create_time']) == date('Y-m-d')){
                    return ['status'=>0, 'msg'=>'您今天已点赞过'];
                }
                break;
            case '2':
                // 转发
                $count = $model->where(['member_no_id'=>$member_no_id, 'source'=>$source, 'create_time'=>['between', today()]])->count();
                if($count >= 10){
                    return ['status'=>0, 'msg'=>'今天转发已达到10次'];
                }
                break;
            case '3':
                // 购买茶叶
                $order = M('order')->where(['code'=>$source_id])->find();
                if(empty($order)){
                    return ['status'=>0, 'msg'=>'今天转发已达到10次'];
                }
                $pay_money = $order['total_amount'];
                if($pay_money < 1){
                    return ['status'=>0, 'msg'=>'下单金额小于1元'];   
                }
                $like_num = floor($pay_money);
                break;
            default:
                return ['status'=>0, 'msg'=>'类型不存在'];
                break;
        }
        $data = [
            'user_id'       => $member_no_info['user_id'],
            'member_no_id'  => $member_no_id,
            'source'        => $source,
            'source_id'     => $source_id,
            'like_num'      => $like_num,
            'create_time'   => time(),
        ];
        $res = $model->add($data);
        if($res){
            M('member_no')->where(['member_no'=>$member_no])->save(['like_time'=>time()]);
            return ['status'=>1, 'msg'=>'ok'];
        }else{
            return ['status'=>0, 'msg'=>'记录失败'];
        }
    }
}
if(!function_exists('like_log')){
    /**
     * [like_log description]
     * @author 张亚伟<1743325520@qq.com>
     * @DateTime 2018-11-29
     * @param    [type]     $user_id   [description]
     * @param    [type]     $source    来源类型 1文章 2棋牌室 3麻将机厂家 4签到奖品 5附近麻将机店商品 6维修工
     * @param    [type]     $source_id [description]
     * @return   [type]                [description]
     */
    function like_log($user_id, $source, $source_id){
        $model = M('like_log');
        $has = $model->where(['user_id'=>$user_id, 'source'=>$source, 'source_id'=>$source_id])->find();
        if(empty($has)){
            switch ($source) {
                case '1':
                    $info = M('article')->where(['id'=>$source_id])->find();
                    if(empty($info)){
                        return ['status'=>0, 'msg'=>'内容不存在'];
                    }
                    $res = M('article')->where(['id'=>$source_id])->setInc('like_num', 1);
                    break;
                case '2':
                    $info = M('shop')->where(['id'=>$source_id])->find();
                    if(empty($info)){
                        return ['status'=>0, 'msg'=>'门店不存在'];
                    }
                    $res = M('shop')->where(['id'=>$source_id])->setInc('like_num', 1);
                    break;
                case '3':
                    $info = M('brand')->where(['id'=>$source_id])->find();
                    if(empty($info)){
                        return ['status'=>0, 'msg'=>'品牌不存在'];
                    }
                    $res = M('brand')->where(['id'=>$source_id])->setInc('like_num', 1);
                    break;
                case '4':
                    $info = M('prizes')->where(['id'=>$source_id])->find();
                    if(empty($info)){
                        return ['status'=>0, 'msg'=>'奖品不存在'];
                    }
                    $res = M('prizes')->where(['id'=>$source_id])->setInc('like_num', 1);
                    break;
                case '5':
                    $info = M('nearby_shop_goods')->where(['id'=>$source_id])->find();
                    if(empty($info)){
                        return ['status'=>0, 'msg'=>'商品不存在'];
                    }
                    $res = M('nearby_shop_goods')->where(['id'=>$source_id])->setInc('like_num', 1);
                    break;
                case '6':
                    $info = M('maintainer')->where(['id'=>$source_id])->find();
                    if(empty($info)){
                        return ['status'=>0, 'msg'=>'维修工不存在'];
                    }
                    $res = M('maintainer')->where(['id'=>$source_id])->setInc('like_num', 1);
                    break;
                default:
                    return ['status'=>0, 'msg'=>'类型不存在'];
                    break;
            }
            if($res){
                $res = $model->add([
                    'user_id'       => $user_id,
                    'source'        => $source,
                    'source_id'     => $source_id,
                    'create_time'   => time(),
                ]);
                if($res){
                    return ['status'=>1, 'msg'=>'点赞成功'];
                }
            }
            return ['status'=>0, 'msg'=>'点赞失败'];
        }else{
            return ['status'=>0, 'msg'=>'已点赞'];
        }
    }
}

function update_pay_status($code)
{
    if(strpos($code, 'JC')!==false){
        // 集采订单
        $order_model = M('jc_order');
        $order = $order_model->where(['order_sn'=>$code])->find();
        if(empty($order)){
            return ['s' => false, 'm'=>'订单不存在'];
        }
        if($order['pay_status']){
            return ['s' => true, 'm'=>'订单已支付'];
        }
        $now_time = time();
        $order_up = [
            'pay_status'    => 1,
            'pay_time'      => $now_time,
            'update_time'   => $now_time,
        ];
        $res = $order_model->where(['id'=>$order['id']])->save($order_up);
        switch ($order['order_type']) {
            case 'member':
            case 'vip_member':
                // 会员订单
                update_member_time($order['user_id'], $order['order_type']);
                break;
            case 'goods':
                // 商品订单
                jc_goods_pay_complete($order['id']);
                break;
            default:
                break;
        }
        return ['s' => true, 'm'=>'ok'];
    }

    if(strpos($code, 'JP')!==false){
        // 精辟话术
        $order_model = M('jp_talk_order');
        $order = $order_model->where(['order_sn'=>$code])->find();
        if(empty($order)){
            return ['s' => false, 'm'=>'订单不存在'];
        }
        if($order['pay_status']){
            return ['s' => true, 'm'=>'订单已支付'];
        }
        $valid_month = yzl_config('jp_talk.jp_valid_month');
        $now_time = time();
        $order_up = [
            'pay_status'    => 1,
            'pay_time'      => $now_time,
            'failure_time'  => strtotime("+".$valid_month.' month'),
            'update_time'   => $now_time,
        ];
        $res = $order_model->where(['id'=>$order['id']])->save($order_up);
        return ['s' => true, 'm'=>'ok'];
    }

    if(strpos($code, 'ZX')!==false){
        //情感咨询师
        $order_model = M('counselor_order');
        $order = $order_model->where(['order_sn'=>$code])->find();
        if(empty($order)){
            return ['s' => false, 'm'=>'订单不存在'];
        }
        if($order['pay_status']){
            return ['s' => true, 'm'=>'订单已支付'];
        }
        $now_time = time();
        $order_up = [
            'pay_status'    => 1,
            'pay_time'      => $now_time,
            'update_time'   => $now_time,
        ];
        $res = $order_model->where(['id'=>$order['id']])->save($order_up);
        return ['s' => true, 'm'=>'ok'];
    }

    $order = M('order')->where(array('code' => $code))->find();
    if(empty($order)){
        return ['s' => false, 'm'=>'订单不存在'];
    }
    if($order['pay_status']){
        return ['s' => true, 'm'=>'订单已支付'];
    }

    $res = M('order')->where(array('code' => $code))->save(array('pay_status' => 1, 'status' => 1));
    
    
    $re = M('order_info')->where(array('code' => $code))->select();
    $is_buy_tea = 0;
    foreach ($re as $key => $value) {
        $list=M('product')->where(array('id'=>$value['pid']))->find();
        if($list && $list['cid'] != 18){
            $is_buy_tea = 1;
        }
        $sales=$list['sales']+$value['num'];
        try {
            M('product')->where(array('id'=>$value['pid']))->data(array('sales'=>$sales))->save();
        } catch(Exception $e) {
            
        }
    }
    // 付款完成
    $orderInfo = M('order')->where(array('code' => $code))->find();
    if($orderInfo){
        $userModel = M('user');
        $user = $userModel->where(['id'=>$orderInfo['uid']])->find();
        if($user){
            $member_no_info = M('member_no')->where(['user_id'=>$orderInfo['uid']])->find();
            if($member_no_info){
                M('member_no')->where(['user_id'=>$orderInfo['uid']])->save(['is_buy'=>1]);
                // 以原价赠送赞数
                $like_num = floor($orderInfo['total_amount']);
                if($like_num > 0){
                    member_no_like($member_no_info['member_no'], 3, $code, $like_num);
                }
            }
            // 累计消费
            $userModel->where(['id'=>$user['id']])->setInc('total_amount', $orderInfo['cprice']);
            // 购买过茶叶
            if($is_buy_tea){
                $userModel->where(['id'=>$orderInfo['uid']])->save(['is_buy_tea'=>1]);
            }

            // 佣金日志
            $distribution_amount = $orderInfo['distribution_amount'];
            // 分销
            if($user['first_leader']){
                // 第一个上级
                $first_ratio = yzl_config('distribution.distribution_first_leader');
                $first_money = $distribution_amount*$first_ratio/100;
                $first_money = round($first_money, 2);
                if($first_money > 0){
                    commission_log($user['first_leader'], 'order', $orderInfo['id'], $orderInfo['id'], '订单号：'.$orderInfo['code'], $first_money);
                }
                // 营业额
                $userModel->where(['id'=>$user['first_leader']])->setInc('turnover', $orderInfo['cprice']);
            }
            if($user['second_leader']){
                // 第二个上级
                $second_ratio = yzl_config('distribution.distribution_second_leader');
                $second_money = $distribution_amount*$second_ratio/100;
                $second_money = round($second_money, 2);
                if($second_money > 0){
                    commission_log($user['second_leader'], 'order', $orderInfo['id'], $orderInfo['id'], '订单号：'.$orderInfo['code'], $second_money);
                }
            }
        }
    }

    if ($res) {
        return ['s' => true, 'm'=>'ok'];
    } else {
        return ['s' => false, 'm'=>'失败'];
    }
}

/**
 * [commission_log description]
 * @author 张亚伟<1743325520@qq.com>
 * @DateTime 2019-03-12
 * @param    [type]     $user_id   [description]
 * @param    [type]     $from_type [description]
 * @param    [type]     $from_id   订单表或退款表id
 * @param    [type]     $order_id  订单id
 * @param    [type]     $desc      [description]
 * @param    [type]     $money     [description]
 * @return   [type]                [description]
 */
function commission_log($user_id, $from_type, $from_id, $order_id, $desc, $money)
{
    $data = [
        'user_id'       => $user_id,
        'from_type'     => $from_type,
        'from_id'       => $from_id,
        'order_id'      => $order_id,
        'desc'          => $desc,
        'money'         => $money,
        'create_time'   => time(),
    ];
    $res = M('commission_log')->add($data);
    if($res){
        if($money != 0){
            $user = M('user')->where(['id'=>$user_id])->find();
            if($user){
                if($money > 0){
                    M('user')->where(['id'=>$user_id])->setInc('daishou_money', $money);
                }else{
                    $daishou_money = $user['daishou_money']+$money;
                    $daishou_money = $daishou_money > 0 ? $daishou_money : 0;
                    M('user')->where(['id'=>$user_id])->save(['daishou_money'=>$daishou_money]);
                }
            }
        }
        return true;
    }else{
        return false;
    }
}

/**
 * 确认收货
 */
function confirm_order_receipt($order_id)
{
    M('order')->where(['id'=>$order_id])->save(['status'=>3, 'receipt_time'=>time()]);
}

if(!function_exists('compareVersion')){
    function compareVersion($v1, $v2) {
        $v1 = explode('.', $v1);
        $v2 = explode('.', $v2);
        $len = max(count($v1), count($v2));
        while (count($v1) < $len) {
            $v1[] = 0;
        }
        while (count($v2) < $len) {
            $v2[] = 0;
        }
        for ($i = 0; $i < $len; $i++) {
            $num1 = $v1[$i];
            $num2 = $v2[$i];
            if ($num1 > $num2) {
                return 1;
            } else if ($num1 < $num2) {
                return -1;
            }
        }
        return 0;
    }
}

if(!function_exists('getIP')){
    // 定义一个函数getIP() 客户端IP，
    function getIP(){            
    if (getenv("HTTP_CLIENT_IP"))
         $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
         $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";

    if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip))          
        return $ip;
    else
        return '';
    }
}
?>